<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="课程名称：" prop="courseName">
        <el-input v-model="queryParams.courseName" type="text" placeholder="请输入课程名称" />
      </el-form-item>
      <el-form-item label="授课老师：" prop="teacherId">
        <el-select v-model="queryParams.teacherId" placeholder="请选择授课老师" clearable filterable>
          <el-option v-for="item in nameList" :key="item.id" :label="item.name" :value="item.id" size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable filterable>
          <el-option v-for="dict in dict.type.interest_class_status" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teachPlanList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" align="center" label="序号" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="授课老师" align="center" prop="teacherName" />
      <!-- <el-table-column label="报名时间" align="center" prop="registrationTime" /> -->
      <el-table-column label="上课时间" align="center" prop="classTime" width="350" />
      <el-table-column label="报名人数" align="center" prop="enrollment">
        <template slot-scope="scope">
          <el-link type="primary" @click="viewEnrollment(scope.row, 1)">{{ scope.row.enrollment }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="取消报名人数" align="center" prop="enrollment">
        <template slot-scope="scope">
          <el-link type="primary" @click="viewEnrollment(scope.row, 2)">{{ scope.row.cancelEnrollment }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.interest_class_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-if="scope.row.status == 0" @click="handlePublish(scope.row)">发布</el-button>
          <el-button icon="el-icon-download" size="mini" v-if="scope.row.status != 0" type="text"
            @click="handleExport(scope.row)">导出</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改教学计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body :close-on-click-modal="false"
      :before-close="cancel">
      <div v-if="title == '课程报名名单' || title == '取消报名名单'">
        <div style="margin-bottom:20px;display: flex;justify-content: space-between;">
          <span v-if="title == '课程报名名单'">
            共有{{ peopleTotal }}人报名
          </span>
          <span v-else>共有{{ peopleTotal }}人取消报名</span>
          <el-button v-if="title == '取消报名名单'" type="primary" @click="exportBtn" size="small">导出</el-button>
        </div>
        <el-table :data="signPeopleList" style="width: 100% height: 500px;overflow: auto;" >
          <el-table-column prop="stuName" label="幼儿姓名" align="center">
          </el-table-column>
          <el-table-column prop="className" label="所属班级" align="center">
          </el-table-column>
          <el-table-column prop="registrationTime" label="报名时间" align="center">
          </el-table-column>
          <el-table-column v-if="title !== '课程报名名单'" prop="cancelRegistrationTime" label="取消报名时间" align="center">
            <template slot-scope="scope">
              <div>
               <span>{{ scope.row.cancelRegistrationTime }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="title == '课程报名名单'" label="操作" align="center">
            <template slot-scope="scope">
              <div>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="cancelBtn(scope.row)">取消报名</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination  :total="peopleTotal" :page.sync="enrollmentParams.pageNum" :limit.sync="enrollmentParams.pageSize"
        @pagination="title == '课程报名名单' ? viewEnrollment(1) : viewEnrollment(2)" /> -->

        <!-- <pagination  :total="peopleTotal" :page.sync="enrollmentParams.pageNum" :limit.sync="enrollmentParams.pageSize"
        @pagination="viewEnrollment()" /> -->

      </div>
      <el-form v-else ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="课程名称：" prop="courseName">
          <el-input v-model="form.courseName" type="text" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="标题图片：" prop="img">
          <imageUpload v-model="form.img" :limit="1" />
        </el-form-item>
        <el-form-item label="课程介绍：" prop="courseIntroduction">
          <el-input v-model="form.courseIntroduction" type="textarea" placeholder="请输入课程介绍" />
        </el-form-item>
        <el-form-item label="招生对象:" prop="enrollmentTargets">
          <el-select v-model="form.enrollmentTargets" multiple clearable placeholder="请选择年级">
            <el-option v-for="dict in dict.type.year_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报名时间：" prop="registrationTime">
          <el-date-picker v-model="form.registrationTime" type="daterange" range-separator="至" format="yyyy-MM-dd"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="{
              disabledDate: (date) => {
                // 获取当前日期对象，并清空其时间部分（只保留日期）
                const today = new Date();
                today.setHours(0, 0, 0, 0);

                // 禁止选择今天的日期之前的所有日期
                return date.getTime() < today.getTime();
              }
            }">
          </el-date-picker>
        </el-form-item>
        <div>
          <el-form-item label="上课时间：" class="required-marker" prop="classTime">
            <!-- 上课时间段 -->
            <el-date-picker v-model="form.beginEndTime" type="daterange" format="yyyy-MM-dd" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="{
                disabledDate: (date) => {
                  // 获取当前日期对象，并清空其时间部分（只保留日期）
                  const today = new Date();
                  today.setHours(0, 0, 0, 0);

                  // 禁止选择今天的日期之前的所有日期
                  return date.getTime() < today.getTime();
                }
              }">
            </el-date-picker>

            <!-- 每周选项 -->
            <div style="display:flex;margin-top:10px">
              <span style="width:80px">每周</span>
              <el-select v-model="form.week" placeholder="请选择" clearable filterable>
                <el-option v-for="dict in weekList" :key="dict" :label="dict" :value="dict">
                </el-option>
              </el-select>
              <!-- 时间点 -->
              <el-time-picker is-range v-model="form.timePoint" range-separator="至" format="HH:mm" value-format="HH:mm"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
              </el-time-picker>
            </div>
          </el-form-item>
        </div>
        <el-form-item label="限制人数："  prop="limitNum" >
          <el-input  v-model="form.limitNum" type="number" placeholder="请输入限制人数"></el-input>
        </el-form-item>
        <el-form-item label="收费标准：" prop="feeStandards">
          <div style="display:flex">
            <el-input v-model="form.feeStandards" type="number"
              @input="form.feeStandards = form.feeStandards.replace(/[^\d|\.]/g, '')" placeholder="请输入收费标准" />元
          </div>
        </el-form-item>
        <el-form-item label="授课老师：" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择授课老师" multiple clearable filterable>
            <el-option v-for="item in nameList" :key="item.id" :label="item.name" :value="item.id + ''" size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="老师介绍：" prop="teacherIntroduction">
          <el-input v-model="form.teacherIntroduction" type="textarea" placeholder="请输入老师介绍" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title == '新增兴趣课'">
        <el-button @click="submitForm(0)">保 存</el-button>
        <el-button type="primary" @click="submitForm(1)">发 布</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="title !== '课程报名名单' && title !== '取消报名名单'" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTeachPlanDetail,
  updateTeachPlangarden,
  exportTeachPlan,
  listTeachPlangarden, addTeachPlangarden, delTeachPlangarden, exportTeachPlangarden
} from '@/api/teach/teachPlan'
import { getInterClassInfo, addInterClassInfo, editInterClassInfo, deleteInterClassInfo, exportCancelEnrollment, exportInterClassInfo, enrollmentList, releaseInterClassInfo, cancelEnrollmentList,cancelCourseRegister } from "@/api/base/interClassManage";
import { getToken } from "@/utils/auth";
import { selectSemster } from "@/api/base/semster";
import { selectClazz } from "@/api/base/clazz";
import { selectCourse } from "@/api/base/course";
import { selectTeacher, teacherNameList } from "@/api/base/teacher";
import { formatDateOnly } from "@/utils";

export default {
  name: "TeachPlan",
  dicts: ['interest_class_status', 'year_type'],
  data() {
    return {
      //最大课时
      periods: 48,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教学计划表格数据
      teachPlanList: [],
      // 学期数据
      semsterList: [],
      // 班级表格数据
      classList: [],
      // 教师表格数据
      teacherList: [],
      // 课程数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      enrollmentParams: {
        pageNum: 1,
        pageSize: 50,
      },
      // 表单参数
      form: {},
      nameList: [],
      signPeopleList: [],
      peopleTotal: null,
      weekList: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'],
      // 表单校验
      rules: {
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        img: [
          { required: true, message: "标题图片不能为空", trigger: "blur" }
        ],
        courseIntroduction: [
          { required: true, message: "课程介绍不能为空", trigger: "blur" }
        ],
        enrollmentTargets: [
          { required: true, message: "招生对象不能为空", trigger: "blur" }
        ],
        registrationTime: [
          { required: true, message: "报名时间不能为空", trigger: "blur" }
        ],
        feeStandards: [
          { required: true, message: "收费标准不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "授课老师不能为空", trigger: "blur" }
        ],
        teacherIntroduction: [
          { required: true, message: "老师介绍不能为空", trigger: "blur" }
        ],
        limitNum: [
          { required: true, message: "限制人数不能为空", trigger: "blur" }
        ],
        classTime: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.beginEndTime || !this.form.week || !this.form.timePoint) {
                callback(new Error('上课时间、每周选项和时间点均需填写'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      exoprdId:null,
      courseId:null
    };
  },
  created() {
    this.getList();
    this.getTeacherList()
    this.getSemster();
    this.getCourse();
    this.getTeacher();
    this.getClazz();
  },
  methods: {
    async getTeacherList() {
      const { rows, code } = await teacherNameList()
      if (code === 200) {
        this.nameList = rows
      } else {
        this.$message.error(msg)
      }
    },
    // 取消报名
   async cancelBtn(row){
    const {code} = await cancelCourseRegister(row.id)
    if(code == 200){
      this.$message.success('取消报名成功')
      this.open = false
      this.getList()
    }
    },
    /**学期切换*/
    changesem(value) {
      this.form.semId = value[0];
      this.form.semName = value[1]
    },
    /**班级*/
    async getClazz() {
      try {
        const { rows } = await selectClazz();
        this.classList = rows
      } catch (e) {
        console.log(e)
      }
    },
    /**教师**/
    async getTeacher() {
      try {
        const { rows } = await selectTeacher();
        this.teacherList = rows;
      } catch (e) {
        console.log(e)
      }
    },
    /**课程*/
    async getCourse() {
      try {
        const { rows } = await selectCourse();
        this.courseList = rows;
      } catch (e) {
        console.log(e)
      }
    },
    /**学期*/
    async getSemster() {
      try {
        const { rows } = await selectSemster();
        this.semsterList = rows;
      } catch (e) {
        console.log(e)
      }
    },
    /** 查询教学计划列表 */
    async getList() {
      try {
        this.loading = true;
        const data = await getInterClassInfo(this.queryParams);
        this.teachPlanList = data.rows;
        this.total = data.total;
        this.loading = false;
      } catch (e) {
        console.log(e)
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        courseName: null,
        img: null,
        courseIntroduction: null,
        enrollmentTargets: null,
        registrationTime: null,
        feeStandards: null,
        teacherId: null,
        teacherIntroduction: null,
        beginEndTime: null,
        week: null,
        timePoint: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增兴趣课";
    },
    // 发布
    async handlePublish(row) {
      row.status = null
      const res = await releaseInterClassInfo(row)
      if (res.code === 200) {
        this.msgSuccess("发布成功");
        this.getList()
      }
    },
    // 查看报名人数
    async viewEnrollment(row, val) {
      const obj = {
        ...this.enrollmentParams,
        courseId:row.id
      }
      this.exoprdId = row.id

      this.open = true
      this.title = val == 1 ? '课程报名名单' : '取消报名名单'
      const res = val == 1 ? await enrollmentList(obj) : await cancelEnrollmentList(obj)
      if (res.code == 200) {
        this.signPeopleList = res.rows
        this.peopleTotal = res.total
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.form = row;
      let timeList = this.form.classTime.split(',')
      let [startDateStr, endDateStr] = timeList[0].split('~');
      const beginEndTime = [new Date(startDateStr), new Date(endDateStr)]
      this.$set(this.form, 'beginEndTime', beginEndTime)
      this.form.week = timeList[1];
      let [startTimeStr, endTimeStr] = timeList[2].split('~');
      this.form.timePoint = [
        startTimeStr,
        endTimeStr
      ];
      this.form.enrollmentTargets = this.form.enrollmentTargets.includes(",") ? this.form.enrollmentTargets.split(',') : [this.form.enrollmentTargets]
      this.form.teacherId = this.form.teacherId.includes(',') ? this.form.teacherId.split(',') : [this.form.teacherId]
      if (this.form.registrationTime.includes("~")) {
        let [reStartTimeStr, reEndTimeStr] = this.form.registrationTime.split('~')
        this.form.registrationTime = [new Date(reStartTimeStr), new Date(reEndTimeStr)]
      }
      // this.form=Object.assign({}, this.form, row)
      this.open = true;
      this.title = "修改兴趣课";
    },
    /** 提交按钮 */
    submitForm(flag) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // console.log('formform',this.form);
          this.form.registrationTime = `${formatDateOnly(this.form.registrationTime[0])}~${formatDateOnly(this.form.registrationTime[1])}`;
          this.form.classTime = `${formatDateOnly(this.form.beginEndTime[0])}~${formatDateOnly(this.form.beginEndTime[1])},${this.form.week},${this.form.timePoint[0]}~${this.form.timePoint[1]}`;
          this.form.enrollmentTargets = this.form.enrollmentTargets.join(',')
          this.form.teacherId = this.form.teacherId.join(',')
          const params = {
            courseName: this.form.courseName,
            img: this.form.img,
            courseIntroduction: this.form.courseIntroduction,
            enrollmentTargets: this.form.enrollmentTargets,
            registrationTime: this.form.registrationTime,
            classTime: this.form.classTime,
            feeStandards: this.form.feeStandards,
            teacherId: this.form.teacherId,
            teacherIntroduction: this.form.teacherIntroduction,
            limitNum:this.form.limitNum
          }
          if (this.form.id != null) {
            params.id = this.form.id
            editInterClassInfo(params).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (flag == 0) params.status = 0
            addInterClassInfo(params).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除id为"' + ids + '"的数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return deleteInterClassInfo(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport(row) {
      const queryParams = {}
      if (row) {
        queryParams.id = row.id
      } else {
        queryParams = this.queryParams
      }
      this.$confirm('是否确认导出该数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportInterClassInfo(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导出按钮操作 */
    exportBtn() {
      const queryParams = this.exoprdId
      this.$confirm('是否确认导出所有取消报名列表?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportCancelEnrollment(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
  }
};
</script>
<style lang="scss" scoped>
.el-dialog__body .el-select,
.el-dialog__body .el-date-editor {
  width: 100%;
}

.required-marker::before {
  content: "*";
  color: red;
  margin-right: 5px;
  position: relative;
  left: 12px;
  top: 26px;
}
</style>
